package light.head.dao.sys;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import light.head.cache.Cache;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.model.OrganType;
import light.head.model.OrganTypeRelation;

import org.springframework.stereotype.Service;

@Service
public class OrganTypeDAO extends BaseDAO<OrganType, Integer> {
	
	private final static String sql_loadAll = "FROM OrganType";

	public RESULT findByMap(Map<String, String> map, PageBean pageBean) {
		StringBuffer hql = new StringBuffer("FROM OrganType ot WHERE 1 = 1");
		
		List<Object> list = null;
		if (map != null) {
			list = new ArrayList<Object>();
			
			String name = map.get(Parm.NAME);
			if (null != name && !"".equals(name)) {
				hql.append(" AND ot.name LIKE ?");
				list.add("%" + name + "%");
			}
		}
		
		hql.append(" ORDER BY ot.code");
		
		if (findToPageBean(hql.toString(), pageBean, list) == RESULT.SUCCESS)
			return RESULT.SUCCESS;
		
		return RESULT.ERROR;
	}
	
	public List<OrganType> getAll() {
		if (null == Cache.organTypeList || Cache.organTypeList.size() == 0)
			return loadAll();
		return Cache.organTypeList;
	}
	public List<OrganType> loadAll() {
		Cache.organTypeList = find(sql_loadAll);
		return Cache.organTypeList;
	}
	
	/**
	 * 该方法是提供给freemarker 使用的，不能重载,否则悲剧
	 * @author YangGuangHe
	 * @Time 2013-10-3 下午5:29:00
	 * @param pc 机构类型编号
	 */
	public List<OrganType> loadByPc(String pc) {
		if (null == pc || Sys.NONE.equals(pc)) {
			return null;
		}
		// 这个是给平台管理员调用时用的
		if (Sys.ZERO == Integer.parseInt(pc)) {
			return this.getAll();
		}
		List<OrganType> list = new ArrayList<OrganType>();
		List<OrganType> cachelist = this.getAll();
		OrganType ot = get(Integer.parseInt(pc));
		if (null != ot) {
			StringBuffer hql = new StringBuffer("FROM OrganTypeRelation otr WHERE otr.gfpCode = ?");
			List<OrganTypeRelation> otrList = find(hql.toString(), Integer.parseInt(pc));
			if (null != otrList && otrList.size() > 0) {
				for (OrganTypeRelation otr : otrList) {
					for (OrganType o : cachelist) {
						if (o.getCode() == otr.getScode()) {
							list.add(o);
						}
					}
				}
			}
			list.add(ot);	// 将父类型添加进去
		}
		return list;
	}
}
